package com.kingdee.eas.hr.affair.client;


import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.ctrl.extendcontrols.KDBizPromptBox;
import com.kingdee.bos.ctrl.kdf.table.*;
import com.kingdee.bos.ctrl.kdf.table.event.KDTEditEvent;
import com.kingdee.bos.ctrl.kdf.util.style.StyleAttributes;
import com.kingdee.bos.ctrl.swing.KDPromptSelector;
import com.kingdee.bos.dao.IObjectValue;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.util.BOSObjectType;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.base.permission.*;
import com.kingdee.eas.basedata.org.*;
import com.kingdee.eas.basedata.org.client.PositionPromptBox2;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.common.client.SysContext;
import com.kingdee.eas.fdc.basedata.FDCSQLBuilder;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.hr.affair.*;
import com.kingdee.eas.hr.base.batch.BatchProcessedResult;
import com.kingdee.eas.hr.base.client.IHRF7CommonRegister;
import com.kingdee.eas.hr.base.client.PlugInUIParam;
import com.kingdee.eas.hr.base.client.f7.EditorCreator;
import com.kingdee.eas.hr.cifihr.BelongFactory;
import com.kingdee.eas.hr.cifihr.BelongInfo;
import com.kingdee.eas.hr.cifihr.DispatchAddressFactory;
import com.kingdee.eas.hr.cifihr.DispatchAddressInfo;
import com.kingdee.eas.hr.cifihr.DispatchTypeFactory;
import com.kingdee.eas.hr.cifihr.DispatchTypeInfo;
import com.kingdee.eas.hr.emp.PersonPositionInfo;
import com.kingdee.eas.util.client.EASResource;
import com.kingdee.eas.util.client.MsgBox;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.util.DateTimeUtils;

import java.sql.SQLException;
import java.util.*;

public class FlucInBizBillEditUIBizCTEx extends FlucInBizBillEditUIBiz {
	
    public void entryEditStopped(KDTEditEvent e)
    throws Exception
{
    int colIndex = e.getColIndex();
    int rowIndex = e.getRowIndex();
    IRow row = kdtEntrys.getRow(rowIndex);
    if(colIndex == kdtEntrys.getColumn("position").getColumnIndex())
    {
        PositionInfo pInfo = (PositionInfo)e.getValue();
        PositionInfo oldPinfo = (PositionInfo)row.getCell("oldPosition").getValue();
        if(pInfo != null && !pInfo.equals(e.getOldValue()))
        {
            if(oldPinfo != null && oldPinfo.getId().equals(pInfo.getId()))
            {
                row.getCell("position").setValue(null);
                throw new HRAffairException(HRAffairException.NEWPOSITION_NOT_SAME_OLD);
            }
            positionChanged(row, pInfo);
        }
    }
    
    if(colIndex == kdtEntrys.getColumn("chkLength").getColumnIndex())
    {
        Date bizDate = (Date)row.getCell("bizDate").getValue();
        Integer chkLength = (Integer)e.getValue();
        if(chkLength != null && bizDate != null)
        {
            Date chkEndDate = DateTimeUtils.addMonth(bizDate, chkLength.intValue());
            row.getCell("chkEndDate").setValue(chkEndDate);
        }
    }
}

protected void initEditor()
    throws Exception
{
    super.initEditor();
    kdtEntrys.getColumn("chkLength").setEditor(EditorCreator.getNumberCellEditor(3, 0, 1));
}

public void registerContextChangeF7(IHRF7CommonRegister register)
{
    super.registerContextChangeF7(register);
    KDBizPromptBox prmtPosition = new KDBizPromptBox();
    register.registerPositionPromptBox2(prmtPosition, kdtEntrys.getColumn("position"));
    PositionPromptBox2 position = (PositionPromptBox2)prmtPosition.getSelector();
    position.setSealUp("true");
}

public void entryEditStopping(KDTEditEvent kdteditevent)
    throws Exception
{
}

protected List getProcessedPersons(List persons, String billID)
    throws Exception
{
    BatchProcessedResult result = AffairBatchProcessFacadeFactory.getRemoteInstance().processPerson(persons, billID);
    if(result == null)
        return null;
    if(result.isHasValidInfo())
        MsgBox.showInfo(result.getInvalidInfo());
    List processedPerson = result.getResult();
    return processedPerson;
}

protected IObjectValue createNewDetailData(PersonInfo pInfo)
{
    FlucInBizBillEntryInfo info = new FlucInBizBillEntryInfo();
    return setPersonValue(info, pInfo);
}

public void addLine(boolean isInsert)
    throws Exception
{
    addEmpPoolF7(isInsert);
}

protected void addEmpPoolF7(boolean isInsert)
    throws Exception
{
    KDBizPromptBox f7 = new KDBizPromptBox();
    f7.setQueryInfo("com.kingdee.eas.hr.affair.app.EmployeePoolListQuery");
    FilterInfo filter = new FilterInfo();
    filter.getFilterItems().add(new FilterItemInfo("source", new Integer(1), CompareType.EQUALS));
    HROrgUnitInfo hro = (HROrgUnitInfo)ctx.getMainOrgContext().get(OrgType.HRO);
    if(hro == null)
    {
        MsgBox.showError(EASResource.getString("com.kingdee.eas.hr.affair.AFFAIRAutoGenerateResource", "55_FlucInBizBillEditUIBiz"));
        return;
    }
    filter.getFilterItems().add(new FilterItemInfo("targetPool.id", hro.getId(), CompareType.EQUALS));
    filter.getFilterItems().add(new FilterItemInfo("targetPool.id", null, CompareType.EQUALS));
    filter.setMaskString("#0 and (#1 or #2)");
    EntityViewInfo ev = new EntityViewInfo();
    ev.setFilter(filter);
    f7.setEntityViewInfo(ev);
    f7.setEnabledMultiSelection(true);
    f7.setDataBySelector();
    if(!f7.getSelector().isCanceled())
    {
        List persons = new ArrayList();
        Map employeePoolMap = new HashMap();
        if(f7.getData() instanceof Object[])
        {
            Object objs[] = (Object[])f7.getData();
            for(int i = 0; i < objs.length; i++)
            {
                EmployeePoolInfo empPoolInfo = (EmployeePoolInfo)objs[i];
                persons.add(empPoolInfo.getPerson());
                employeePoolMap.put(empPoolInfo.getPerson().getId().toString(), empPoolInfo);
            }

        } else
        {
            EmployeePoolInfo empPoolInfo = (EmployeePoolInfo)f7.getData();
            persons.add(empPoolInfo.getPerson());
            employeePoolMap.put(empPoolInfo.getPerson().getId().toString(), empPoolInfo);
        }
        addLineByPersonList(persons, true);
        afterAddEmpPool(employeePoolMap);
    }
}

protected void afterAddEmpPool(Map employeePoolMap)
{
    for(int i = 0; i < kdtEntrys.getRowCount(); i++)
    {
        IRow row = kdtEntrys.getRow(i);
        PersonInfo person = (PersonInfo)row.getCell("person").getValue();
        EmployeePoolInfo empPoolInfo = (EmployeePoolInfo)employeePoolMap.get(person.getId().toString());
        String oldAdminID = ((AdminOrgUnitInfo)row.getCell("oldAdminOrg").getValue()).getId().toString();
        EntityViewInfo View = new EntityViewInfo();
	    FilterInfo filter = new FilterInfo();
	    filter.getFilterItems().add(new FilterItemInfo("person.id",person.getId().toString()));
		filter.getFilterItems().add(new FilterItemInfo("oldAdminOrg.id",oldAdminID));
		View.setFilter(filter);
		try {
			FlucOutBizBillEntryCollection EntryColl = FlucOutBizBillEntryFactory.getRemoteInstance().getFlucOutBizBillEntryCollection(View);
			if(EntryColl.size()>0){
				FlucOutBizBillEntryInfo  info = EntryColl.get(0);
				FDCSQLBuilder sql = new FDCSQLBuilder();
			    sql.appendSql("select * from T_HR_FlucOutBizBillEntry where fid='"+ info.getId().toString() + "'");
	   	        String oldBlongID=null; 
	   	        String newBlongID=null;
	   	        String dispatchTypeID=null;
	   	        String dispatchAdressID=null;
	   	        String oldcompanyID=null;
	   	 	    IRowSet rowset = sql.executeQuery();
	   	 	   while(rowset.next()){
	   	 		 oldBlongID = rowset.getString("cfoldBlongID");
	   	 		 newBlongID = rowset.getString("cfnewBlongID");
	   	 		 dispatchTypeID = rowset.getString("cfdispatchTypeId");
	   	 		 dispatchAdressID = rowset.getString("cfdispatchAdressId");
	   	 	     break;
	   	 	   }
			    if(oldBlongID!=null){
			    	BelongInfo oldBInfo = BelongFactory.getRemoteInstance().getBelongInfo(new ObjectUuidPK(oldBlongID));
					row.getCell("oldBlong").setValue(oldBInfo);
	   	        }
			    if(newBlongID!=null){
			    	BelongInfo newBInfo = BelongFactory.getRemoteInstance().getBelongInfo(new ObjectUuidPK(newBlongID));
					row.getCell("newBlong").setValue(newBInfo);
	   	        }
	   	        if(dispatchTypeID!=null){
	   	        	DispatchTypeInfo disInfo = DispatchTypeFactory.getRemoteInstance().getDispatchTypeInfo(new ObjectUuidPK(dispatchTypeID));
	   	            row.getCell("dispatchType").setValue(disInfo);
	   	        }
	   	       if(dispatchAdressID!=null){
	   	    	   DispatchAddressInfo adressInfo = DispatchAddressFactory.getRemoteInstance().getDispatchAddressInfo(new ObjectUuidPK(dispatchAdressID));
	   	           row.getCell("dispatchAdress").setValue(adressInfo);
	   	        }
			}
		} catch (BOSException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (EASBizException e) {
			e.printStackTrace();
		}
        if(empPoolInfo != null && empPoolInfo.getBizSignal() == 1)
            row.getCell("holdPosition").setValue(new Boolean(true));
    }

}

public void handleNewData(CoreBaseInfo info)
    throws Exception
{
    super.handleNewData(info);
    List persons = new ArrayList();
    if(info != null && info.get("entrys") != null)
    {
        FlucInBizBillEntryCollection fluCol = (FlucInBizBillEntryCollection)info.get("entrys");
        int i = 0;
        for(int n = fluCol.size(); i < n; i++)
        {
            FlucInBizBillEntryInfo flucInfo = fluCol.get(i);
            persons.add(flucInfo.getPerson());
        }

        if(persons != null && persons.size() > 0)
        {
            persons = getProcessedPersons(persons, null);
            i = 0;
            for(int n = persons.size(); i < n; i++)
            {
                PersonInfo pInfo = (PersonInfo)persons.get(i);
                int k = 0;
                for(int j = fluCol.size(); k < j; k++)
                {
                    FlucInBizBillEntryInfo flucInfo = fluCol.get(i);
                    if(pInfo.getId().toString().equals(flucInfo.getPerson().getId().toString()))
                        setPersonValue(flucInfo, pInfo);
                }

            }

        }
    }
}

private FlucInBizBillEntryInfo setPersonValue(FlucInBizBillEntryInfo info, PersonInfo pInfo)
{
    info.setPerson(pInfo);
    PersonPositionInfo ppInfo = (PersonPositionInfo)pInfo.get("personPosition");
    if(ppInfo != null)
    {
        info.setOldJobGrade(ppInfo.getJobGrade());
        info.setOldJobLevel(ppInfo.getJobLevel());
        info.setOldPosition(ppInfo.getPrimaryPosition());
        info.setOldAdminOrg(ppInfo.getPersonDep());
        if(ppInfo.getPrimaryPosition() != null)
            info.setOldJob(ppInfo.getPrimaryPosition().getJob());
    }
    return info;
}

protected void initEmpPoolFu()
{
}

protected boolean isAddPersonByF7()
{
    return true;
}

protected String[] getNotNullColumn()
{
    return (new String[] {
        "position", "adminOrg", "bizDate"
    });
}

protected String[] getNotDupColumn()
{
    return (new String[] {
        "person"
    });
}

protected String getPrintQuery(String dsName)
{
    getClass();
    if("baseInfo".equals(dsName))
        return "com.kingdee.eas.hr.affair.app.FlucInBizBillPrintQuery";
    getClass();
    if("approveInfo".equals(dsName))
        return "com.kingdee.eas.hr.affair.app.FlucInBizBillApprovePrintQuery";
    else
        return null;
}

protected String getPrintPath()
{
    return "/HR/AffairBiz/FlucIn";
}

public void initDataStatus()
    throws Exception
{
    super.initDataStatus();
    UserInfo userInfo = SysContext.getSysContext().getCurrentUserInfo();
    HROrgUnitInfo hrOrgInfo = SysContext.getSysContext().getCurrentHRUnit();
    IPermission per = PermissionFactory.getRemoteInstance();
    FieldPermission fields = per.getFieldPermission(BOSObjectType.create("E41B9A4E"), new ObjectUuidPK(userInfo.getId()), new ObjectUuidPK(hrOrgInfo.getId()));
    IColumn col = kdtEntrys.getColumn(getJobLevelCol());
    FieldAccessInfo accessInfo = fields.getFieldAccessInfo("entrys.jobLevel");
    if(accessInfo != null && !accessInfo.isEditable() && col != null)
        col.getStyleAttributes().setBackground(CANNOT_INPUT_COLOR);
    col = kdtEntrys.getColumn(getJobGradeCol());
    accessInfo = fields.getFieldAccessInfo("entrys.jobGrade");
    if(accessInfo != null && !accessInfo.isEditable() && col != null)
        col.getStyleAttributes().setBackground(CANNOT_INPUT_COLOR);
}

}
